//
//  CacheManager.m
//  CacheManager
//
//  Created by apple on 12-10-21.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "CacheManager.h"
#import "XDBManage.h"

@implementation CacheManager
@synthesize  dictinary,directoryPath;

-(id)init
{
   
     dictinary=[[NSMutableDictionary alloc]init]; 
    //获取程序的 Library/Caches 文件夹
    directoryPath=[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"]; 
    NSLog(@"Caches文件夹路径 = %@",directoryPath);
     [self getDictinaryFromDB];
    return self;
}
-(void)getDictinaryFromDB
{
    
   
    NSMutableArray *checkDic=[[NSMutableArray alloc]init];
    FMDatabase *db=[XDBManage getLocalDatabase];
    FMResultSet *fResult=[db executeQuery:@"SELECT * FROM CacheInfo"];
    while (fResult.next)
    {
        NSMutableDictionary *tmpItem=[[NSMutableDictionary alloc]init];
        
        NSString *Key=[fResult stringForColumn:@"Key"];
        NSString *FileName=[fResult stringForColumn:@"FileName"];
        NSString *ExpiryDate=[fResult stringForColumn:@"ExpiryDate"];
        //将缓存图片的基本信息打包成tempItem 
        [tmpItem setObject:FileName forKey:@"FileName"];
        [tmpItem setObject:ExpiryDate forKey:@"ExpiryDate"];
        //将tempItem 存入dictinary中，key=图片的url链接
        [dictinary setObject:tmpItem forKey:Key];
        NSLog(@"tmpItem=%@",tmpItem);
        NSLog(@"dictinary=%@",dictinary);
        
        NSDate *newdate=[NSDate date];
        NSString *newstring=[NSString stringWithFormat:@"%@",newdate];
        if([newstring compare:ExpiryDate]>=0) //检查缓存是否过期
        {
            [checkDic addObject:Key];//缓存过期加入待删除表中
        }
        
        
   
        
        
    }
    [db close];
    
    //取出待删除表中的数据
    NSEnumerator *enumerator =[checkDic objectEnumerator];
    NSString *mykey;
    while (mykey=(NSString *)[enumerator nextObject])
    {
        //删除过期缓存
        [self checkOverdueCache:mykey];
        
        
    }
    
}


- (void)viewDidUnload
{
  
    //[super viewDidUnload];
    // Release any retained subviews of the main view.
}


-(UIImage *)setImageFromURL:(NSString *)urlPath
{
    if([dictinary objectForKey:urlPath]!=nil)
    {
        NSLog(@"从本地获得");
//        NSMutableDictionary *tempItem=[[NSMutableDictionary alloc]init];
//        tempItem=(NSMutableDictionary *)[dictinary objectForKey:urlPath];
//        return  [self loadImage:[tempItem objectForKey:@"FileName"]]; 
        
        //修改
         return  [self loadImage:urlPath]; 
    }
    else {
        NSLog(@"从网站获得");
        UIImage *image=[self getImageFromURL:urlPath];
        [self saveImage:image withFileURL:urlPath];
        return image;
        
        
        
    }
}


-(void)checkOverdueCache:(NSString*)Key; 
{
    
    NSMutableDictionary *myitem=[[NSMutableDictionary alloc]init];
    myitem=[dictinary objectForKey:Key];
    NSString*ExpiryDate=[myitem objectForKey:@"ExpiryDate"];
    NSLog(@"！！！ExpiryDate=%@",ExpiryDate);
    NSDate *newdate=[NSDate date];
    NSString *newstring=[NSString stringWithFormat:@"%@",newdate];
    
    NSLog(@"!!!newstring=%@",newstring);
    if([newstring compare:ExpiryDate]>=0)
    {
        
        NSLog(@"!!!newstring=%@",newstring);
        NSLog(@"！！！ExpiryDate=%@",ExpiryDate);
        NSLog(@"cache过期，将进行删除");
        //执行删除
        [self removeOverdueCache:Key];
    }else {
        
        NSLog(@"!!!newstring=%@",newstring);
        NSLog(@"！！！ExpiryDate=%@",ExpiryDate);
        NSLog(@"cache不会过期");
    }
    
    
}

-(void) saveCacheDataToDB:(NSString*)url
{
    NSString *name= [NSString stringWithFormat:[url stringByReplacingOccurrencesOfString:@":" withString:@"."]];
    name= [name stringByReplacingOccurrencesOfString:@"/" withString:@"."];
    NSLog(@"url--------------->>>>>>>>!!!!!!!!!!!------->>>>>%@",url);
    NSLog(@"name=%@",name);
    NSMutableDictionary *tmpItem=[[NSMutableDictionary alloc]init];
    NSDate *EndDate=[NSDate date];
   // NSDate *ExpiryDate=[EndDate dateByAddingTimeInterval:20];//缓存保存20秒
    NSDate *ExpiryDate=[EndDate dateByAddingTimeInterval:10*60*24*60];//缓存保存10天
    [tmpItem setObject:EndDate forKey:@"EndDate"];
    [tmpItem setObject:name forKey:@"FileName"];
    [tmpItem setObject:ExpiryDate forKey:@"ExpiryDate"];
    NSLog(@"tmpItem=%@",tmpItem);
    
    [dictinary setObject:tmpItem forKey:url];
    NSLog(@"dictinary%@",dictinary);
    FMDatabase *db=[XDBManage getLocalDatabase];
    [db open];
    NSString *exequery=[NSString stringWithFormat:@"INSERT INTO CacheInfo(FileName, Key,EndDate,ExpiryDate) VALUES('%@','%@','%@','%@');",name,url,EndDate,ExpiryDate];
    
    
    
    if([db executeUpdate:exequery]==YES){
        NSLog(@"写如数据库成功");
    }
    else {
        NSLog(@"写如数据库失败");
    }
    NSLog(@"exequery%@",exequery);
    
    
    
}



-(void)removeOverdueCache:(NSString*)removeURL
{
    NSString *name= [NSString stringWithFormat:[removeURL stringByReplacingOccurrencesOfString:@":" withString:@"."]];
    name= [name stringByReplacingOccurrencesOfString:@"/" withString:@"."];
    NSLog(@"name=%@",name);
    [dictinary removeObjectForKey:removeURL];
    NSLog(@"dictinary%@",dictinary);
    FMDatabase *db=[XDBManage getLocalDatabase];
    [db open];
    NSString *exequery=[NSString stringWithFormat:@"DELETE FROM CacheInfo WHERE Key='%@';",removeURL];
    
    
    NSLog(@"\n删除语句=%@",exequery);
    
    if([db executeUpdate:exequery]==YES){
        NSLog(@"删除数据库成功");
        //删除本地缓存的图片
        [self removeImageFromDisk:removeURL];
    }
    else {
        NSLog(@"删除数据库失败");
    }
    [db close];
    
}

-(void)removeImageFromDisk:(NSString*)removeURL
{
    NSLog(@"开始删除图片");
    NSString *name= [NSString stringWithFormat:[removeURL stringByReplacingOccurrencesOfString:@":" withString:@"."]];
    name= [name stringByReplacingOccurrencesOfString:@"/" withString:@"."];
    name=[NSString stringWithFormat:@"%@.jpg",name];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSArray *contents = [fileManager contentsOfDirectoryAtPath:directoryPath error:NULL];  
    NSEnumerator *e = [contents objectEnumerator];
    
    NSString *filename;
    while ((filename = [e nextObject])) {
        
        if ([filename isEqualToString:name]) {
            
            [fileManager removeItemAtPath:[directoryPath stringByAppendingPathComponent:filename] error:NULL];
        }
    } 
}


-(UIImage *) getImageFromURL:(NSString *)fileURL {
    NSLog(@"执行图片下载函数");
    UIImage * result;
    
    NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
    result = [UIImage imageWithData:data];
    
    return result;
}


-(void) saveImage:(UIImage *)image withFileURL:(NSString *)FileURL
{
    NSString *imageName=[FileURL stringByReplacingOccurrencesOfString:@"/" withString:@"."];
    imageName=[imageName stringByReplacingOccurrencesOfString:@":" withString:@"."];
   // imageName=[imageName stringByReplacingOccurrencesOfString:@"-" withString:@"."];
    NSLog(@"imageName%@",imageName);
    [UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"jpg"]] options:NSAtomicWrite error:nil];
    NSLog(@"保存到本地");
    
    [self saveCacheDataToDB:FileURL];
    
}


-(UIImage *) loadImage:(NSString *)urlPath {
    
    NSMutableDictionary *tempItem=[[NSMutableDictionary alloc]init];
    
    tempItem=(NSMutableDictionary *)[dictinary objectForKey:urlPath];
    NSLog(@"loadImage tempItem%@",tempItem);
    NSString *fileName=[tempItem objectForKey:@"FileName"];
    NSLog(@"loadImage  fileName------->>>>!!!!!!%@",fileName);
    UIImage * result = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.%@", directoryPath, fileName,@"jpg"]];
    return result;
    
    
//    //更新字典中的 对应图片的  ExpiryDate属性
//    NSDate *newdate=[NSDate date];
//    NSLog(@"newdate1=%@",newdate);
//    newdate=[newdate dateByAddingTimeInterval:20];
//    NSLog(@"newdate2%@",newdate);
//    [tempItem removeObjectForKey:@"ExpiryDate"];
//    [tempItem setObject:newdate forKey:@"ExpiryDate"];
//    [dictinary removeObjectForKey:urlPath];
//    NSLog(@"删除后的dictinary%@",dictinary);
//    [dictinary setObject:tempItem forKey:urlPath];
//    NSLog(@"添加后的dictinary%@",dictinary);
//    NSString* name=fileName;
//    //NSString* url;
//    NSString* EndDate=(NSString *)[tempItem objectForKey:@"EndDate"];
//    //NSString* ExpiryDate;
//    
//    NSString *datestring=[NSString stringWithFormat:(NSString*)newdate];
//      //更新数据库中的 ExpiryDate属性
//    FMDatabase *mydb=[XDBManage getLocalDatabase];
//    [mydb open];
////    NSString *exequery=[NSString stringWithFormat:@"UPDATE CacheInfo SET ExpiryDate=‘%@’ WHERE Key='%@';",datestring,urlPath];
//    
//    NSString *exequery1=[NSString stringWithFormat:@"DELETE FROM CacheInfo WHERE Key='%@';",urlPath];
//    NSLog(@"\n更新语句=%@",exequery1);
//    
//    if([mydb executeUpdate:exequery1]==YES){
//        NSLog(@"loadImage 删除数据库成功");
//        //删除本地缓存的图片
//        
//    }
//    else {
//        NSLog(@"oadImage 删除数据库失败");
//    }
//     [mydb close];
//    FMDatabase *mydb2=[XDBManage getLocalDatabase];
//    [mydb open];
//
//     NSString *exequery2=[NSString stringWithFormat:@"INSERT INTO CacheInfo(FileName, Key,EndDate,ExpiryDate) VALUES('%@','%@','%@','%@');",name,urlPath,EndDate,datestring];
//    if([mydb2 executeUpdate:exequery2]==YES){
//        NSLog(@"loadImage 插入数据库成功");
//        //删除本地缓存的图片
//        
//    }
//    else {
//        NSLog(@"loadImage 插入数据库失败");
//    }
//    
//    [mydb close];
//
//   

    
    
    
}

@end
